// hero.js
class Hero {
  constructor(config) {
    this.bg = config.bg;
    this.width = config.width;
    this.height = config.height;
    this.speed = config.speed;
    this.x = 0;
    this.y = 0;
    this.bulletList = [];
    this.bulletClass = Bullet;
    this.bulletConfig = Bullet1Config;
    this.lastShotTime = 0; // 上次射击的时间
    this.shotInterval = config.shotInterval || 500; // 射击间隔，默认为 500 毫秒
    // 销毁状态
    this.destroy = false;
    this.heroLiveIndex = 0;
    this.heroDeathIndex = 0;
    //   当前图片
    this.img = this.bg.live[0]; // 初始图片
    this.lastTime = 0; // 用于动画间隔控制
    this.alive = true;
  }

  // 判断英雄是否碰撞
  collide() {
    this.alive = false;
  }

  // 英雄移动
  move(x, y) {
    this.x = x;
    this.y = y;
  }

  // 英雄射击
  shot() {
    const currentTime = Date.now();
    if (currentTime - this.lastShotTime < this.shotInterval) {
      return; // 射击间隔未到，不射击
    }
    this.lastShotTime = currentTime;

    if (this.bulletClass === Bullet2 && Firepower >= 2) {
      Firepower -= 2;
    } else if (this.bulletClass === Bullet2 && Firepower < 2) {
      return; // 火力值不足，不射击
    }

    let bullet = new this.bulletClass(
      this.bulletConfig,
      this.x + this.width / 2 - this.bulletConfig.width / 2,
      this.y - this.bulletConfig.height
    );
    this.bulletList.push(bullet);
  }

  //判断是否死亡
  judge() {
    const currentTime = Date.now();
    if (currentTime - this.lastTime > this.speed) {
      if (this.alive) {
        this.img = this.bg.live[this.heroLiveIndex++ % this.bg.live.length];
      } else {
        this.img = this.bg.death[this.heroDeathIndex++];
        if (this.heroDeathIndex === this.bg.death.length) {
          this.destroy = true;
        }
      }
      this.lastTime = currentTime;
    }
  }

  paint(context) {
    if (this.img) {
      context.drawImage(this.img, this.x, this.y, this.width, this.height);
    }
  }
}
